package com.test.fundible.fundible_07_loan_status;

import static com.test.fundible.fundible_00_utils.FundibleUtil.startLoading;
import static com.test.fundible.fundible_00_utils.FundibleUtil.stopLoading;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.test.fundible.R;
import com.test.fundible.fundible_00_utils.Loading_fundibleDialog;
import com.test.fundible.fundible_04_home.MainAct_fundibleivity;
import com.test.fundible.fundible_01_launcher.App_fundibleShow_fundibleCustomize;
import com.test.fundible.fundible_01_launcher.Recommend_fundibleAppInfo;
import com.test.fundible.fundible_05_process.Pro_fundiblecessIn_fundiblefo;
import com.test.fundible.fundible_06_loan_apply.LoanApplyDetail;
import com.test.fundible.fundible_00_http.OkHttpUtil;
import com.test.fundible.fundible_00_utils.FundibleUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class LoanStat_fundibleeFailFrag_fundiblement extends Base_fundibleLnFragment {


    private SwipeRefreshLayout refreshLayout;
    private TextView descTv;
    private View recommendView;
    private LinearLayout recommendGroupLayout;

    private TextView loanAmountTv;
    private TextView loanTermTv;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_fundibleloan_state_fail, container, false);

        refreshLayout = view.findViewById(R.id.ffsf_refreshlayout);
        descTv = view.findViewById(R.id.ffsf_tv_desc);
        recommendView = view.findViewById(R.id.ffsf_view_recommend);
        recommendGroupLayout = view.findViewById(R.id.ffsf_layout_recommend_group);

        loanAmountTv = view.findViewById(R.id.ffsf_tv_loan_amount);
        loanTermTv = view.findViewById(R.id.ffsf_tv_loan_term);

        refreshLayout.setOnRefreshListener(() -> {
            startLoading(requireContext(),"");
            OkHttpUtil.getInstance_fundible().uploadEventPoint("REJECT","REFRESH_PULL","");
            OkHttpUtil.getInstance_fundible().requestUsPrcs(
                () -> {
                    String state = Pro_fundiblecessIn_fundiblefo.getInstance_fundible().getFundibleUtil();
                    if (FundibleUtil.isStateChange_fundible(state)) {//刷新用户状态
                        stopLoading();
                        FragmentActivity activity = requireActivity();
                        FundibleUtil.clearState_fundible();
                        activity.startActivity(new Intent(activity, MainAct_fundibleivity.class));
                        activity.finish();
                    }else OkHttpUtil.getInstance_fundible().fetchLnAplDetail(this::refreshLoanDetail);
                }
            );
            refreshLayout.setRefreshing(false);
        });

        startLoading(requireContext(),"");
        OkHttpUtil.getInstance_fundible().fetchLnAplDetail(this::refreshLoanDetail);

        return view;
    }


    @SuppressLint("SetTextI18n")
    public void refreshLoanDetail(){

        //提示文案显示
        descTv.setText(getString(R.string.loan_fail_tv_desc, LoanApplyDetail.getInstance_fundible().getReApplyDate()));

        //额度和日期显示
        String currency = LoanApplyDetail.getInstance_fundible().getCurrency_fundible();
        loanAmountTv.setText(LoanApplyDetail.getInstance_fundible().getAmount_fundible()+" "+currency);
        loanTermTv.setText(LoanApplyDetail.getInstance_fundible().getTermStr_fundible());

        //app推荐显示
        refreshRecommendAppList_fundible();

    }


    public void refreshRecommendAppList_fundible(){

        stopLoading();

        recommendGroupLayout.removeAllViews();

        if (!App_fundibleShow_fundibleCustomize.getInstance_fundible().getRecommendFlag_fundible()) {
            recommendView.setVisibility(View.GONE);
            return;
        }
        recommendView.setVisibility(View.VISIBLE);
        ArrayList<Recommend_fundibleAppInfo> recommendAppInfos = App_fundibleShow_fundibleCustomize.getInstance_fundible().getRecommendAppList_fundible();
        for (Recommend_fundibleAppInfo recommendAppInfo:recommendAppInfos){
            addRecommendApp_fundible(recommendAppInfo);
        }
    }

    //添加推荐App
    private void addRecommendApp_fundible(Recommend_fundibleAppInfo recommendAppInfo){
        View itemView = LayoutInflater.from(requireContext()).inflate(R.layout.item_fundible_recommend_app,null);

        ImageView appLogoIv = itemView.findViewById(R.id.iraa_iv_app_logo);
        TextView appNameTv = itemView.findViewById(R.id.iraa_tv_app_name);
        TextView appAmountTv = itemView.findViewById(R.id.iraa_tv_app_amount);
        TextView appRateTv = itemView.findViewById(R.id.iraa_tv_app_rate);
        TextView appDownloadTv = itemView.findViewById(R.id.iraa_tv_app_download);
        View installBtn = itemView.findViewById(R.id.iraa_btn_install);

        appNameTv.setText(recommendAppInfo.getAp_fundiblepName());
        appAmountTv.setText(recommendAppInfo.getAmou_fundiblentText());
        appRateTv.setText(recommendAppInfo.getSc_fundibleore());
        appDownloadTv.setText(recommendAppInfo.getDow_fundiblenloads());

        //Install按键
        installBtn.setOnClickListener(v -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint("REJECT","RECOMMEND_"+recommendAppInfo.getAp_fundiblepName().toUpperCase()+"_INSTALL_CLICK","");
            String path = recommendAppInfo.getP_fundibleath();
            if (!TextUtils.isEmpty(path))
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(path)));
        });
        //加载logo
        if (recommendAppInfo.getLogo_fundibleBitmap()==null){
            new Thread(() -> {
                try {
                    String logoPath = recommendAppInfo.getL_fundibleogo();
                    if (TextUtils.isEmpty(logoPath)) return;
                    URL url = new URL(logoPath);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode()==200){
                        InputStream inputStream = connection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        recommendAppInfo.setLo_fundiblegoB_fundibleitmap(bitmap);
                        FundibleUtil.safeRun(() -> appLogoIv.setImageBitmap(bitmap));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }else appLogoIv.setImageBitmap(recommendAppInfo.getLogo_fundibleBitmap());

        recommendGroupLayout.addView(itemView);
    }

    @Override
    public void onResume() {
        super.onResume();
        OkHttpUtil.getInstance_fundible().uploadEventPoint("REJECT","START","");
    }

    @Override
    public void onPause() {
        super.onPause();
        OkHttpUtil.getInstance_fundible().uploadEventPoint("REJECT","END","");
    }

}